package com.wfcm.controller;

import com.wfcm.annotation.IgnoreSign;
import com.wfcm.annotation.IgnoreToken;
import com.wfcm.entity.*;
import com.wfcm.service.*;
import com.wfcm.utils.DateUtil;
import com.wfcm.utils.ISsoLoginHelper;
import com.wfcm.utils.R;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @content 后台管理系统小功能Controller
 */
@RequestMapping("/houtai")
@Controller
public class HoutaiController {

    private Logger log = LoggerFactory.getLogger(AdInfoController.class);
    @Autowired
    WfMemberCouponsService memberCouponsService;
    @Autowired
    private WfMemberService memberService;
    @Autowired
    private WfMemberInvitationService memberInvitationService;
    @Autowired
    private DistributionService distributionService;
    @Autowired
    private WfGoodsOrderRelationService goodsOrderRelationService;
    @Autowired
    private WfMemberGiveCoinLogService memberGiveCoinLogService ;
    /**
     * 绑定邀请人关系
     */
    @RequestMapping("/bind")
    @IgnoreToken
    @ResponseBody
    public R login(String mobile,String inviterdMobile ) {
        //判断用户是否存在
        WfMemberEntity  member = memberService.queryByMobile(mobile);
        WfMemberEntity  inviterMember = memberService.queryByMobile(inviterdMobile);

        //判断邀请人id是否为空，若不为空，则添加邀请记录
        WfMemberInvitationEntity memberInvitationEntity = new WfMemberInvitationEntity();
        memberInvitationEntity.setInviterid(member.getUserid());
        memberInvitationEntity.setInvitedid(inviterMember.getUserid());
        memberInvitationEntity.setCreatetime(new Date());
        memberInvitationService.save(memberInvitationEntity);

        return R.ok();
    }

    /**
     * 根据订单赠送邀请人奖励铜钱
     */
    @RequestMapping("/giveCoin")
    @IgnoreToken
    @ResponseBody
    public R giveCoin(String orderNum,String mobile,String inviterdMobile ){
        //获取邀请人 和 被邀请人
        WfMemberEntity  member = memberService.queryByMobile(mobile);
        WfMemberEntity  inviterdMember = memberService.queryByMobile(inviterdMobile);

        Map<String, Object>  map4 = new HashMap<>();
        map4.put("orderCode", orderNum);

        goodsOrderRelationService.queryList(map4).forEach(item -> {
            if (distributionService.searchGoods(item.getGoodsid(), item.getGoodssort())) {
                BigDecimal decimal = new BigDecimal(0);
                Integer commissionRate = distributionService.searchGoodsInfo
                        (item.getGoodsid(), item.getGoodssort()).getCommissionRate();
                decimal = decimal.add(item.getOldcoppercash() != null ? item.getOldcoppercash() : new BigDecimal(0))
                        .add(item.getNewcoppercash() != null ? item.getNewcoppercash() : new BigDecimal(0))
                        .add(item.getGold() != null ? item.getGold() : new BigDecimal(0))
                        .add(item.getRealpay() != null ? item.getRealpay() : new BigDecimal(0))
                        .add(item.getNewGold() != null ? item.getNewGold() : new BigDecimal(0))
                        .multiply(new BigDecimal(commissionRate)).divide(new BigDecimal(100));
                WfMemberGiveCoinLogEntity reward = new WfMemberGiveCoinLogEntity();
                reward.setUserid(member.getUserid());
                reward.setTouserid(inviterdMember.getUserid());
                reward.setType(1); // 1 赚 2 花
                reward.setStatus(2); // 1 审核中 2 成功
                reward.setSource(2);
                reward.setCoinvalue(decimal);
                reward.setCreatetime(new Date());
                reward.setOrdercode(orderNum);
                reward.setRemarkinfo("邀请用户买课赠送铜钱");
                memberGiveCoinLogService.save(reward);
                Long time = System.currentTimeMillis() / 1000;
                distributionService.addRecord(new Distribution(member.getUserid(), inviterdMember.getUserid(), orderNum, decimal.doubleValue(),
                        1, time.intValue(), time.intValue(), item.getGoodsid(), item.getGoodssort(), commissionRate));
            }
        });

        return R.ok();
    }



    /**
     * 根据订单赠送免费课程
     */
    @RequestMapping("/giveFreeCourse")
    @IgnoreToken
    @ResponseBody
    @IgnoreSign
    public R giveFreeCourse( ){
        Map<String,Object> map =new  HashMap();
        Map<String,Object> map1 =new  HashMap();
        map.put("goodsId","146");
        List<WfGoodsOrderRelationEntity> courseList =  goodsOrderRelationService.queryYDLJ(map);//根据订单号获取其中的课程
        BigDecimal zero = BigDecimal.ZERO;
        for(int j=0 ; j<courseList.size(); j++) {
            int userid =  courseList.get(j).getUserid();
            map1.put("uid",userid);
            map1.put("goodsId","139");
            List<WfGoodsOrderRelationEntity> courseList1 =  goodsOrderRelationService.queryYDLJ(map1);
            if(courseList1.size()<1) {
                WfGoodsOrderRelationEntity goodsOrderRelation = new WfGoodsOrderRelationEntity();
                goodsOrderRelation.setAllCash(139,zero, 1, zero, zero, zero, zero,zero);
                goodsOrderRelation.setRealpay(zero);//微信消费
                goodsOrderRelation.setCouponscash(zero);
                /*String orderNum = DateUtil.getOrderCode();*///根据当前时间生成订单号，yyMMddHHmmssSSS + 6位随机数
                goodsOrderRelation.setPart(courseList.get(j).getOrdercode(),1,0,2,0,zero,"3.0",userid,new Date(),4);//Isevaluate是否评价（1是2否）; Backflag是否退货(0.否 1.是)
                goodsOrderRelationService.save(goodsOrderRelation);//保存
            }
        }

        return R.ok();
    }

}









